import axios from "axios";
import io from "socket.io-client";

const socket = io("http://localhost:9999");

const MSG_LIST = "MSG_LIST";
const MSG_REC = "MSG_REC";
const MSG_READ = "MSG_READ";

const initState = {
  chatMsgList: [],
  users: {},
  unread: 0
};

export function chatMsg (state = initState, action) {
  switch (action.type) {
    case MSG_LIST:
      return {
        ...state,
        chatMsgList: action.payload.chatMsgList,
        users: action.payload.users,
        unread: action.payload.chatMsgList.filter(m => !m.read && m.to === action.payload.userId).length
      };
    case MSG_REC:
      const n = action.payload.userId === action.payload.msg.to ? 1 : 0;
      return {
        ...state,
        chatMsgList: [...state.chatMsgList, action.payload.msg],
        unread: state.unread + n
      };
    case MSG_READ:
      return {
        ...state,
        chatMsgList: state.chatMsgList.map(function (m) {
          m.from === action.payload.from && m.to === action.payload.to ?
            m.read = true : m.read = m.read;
          return m;
        }),
        unread: state.unread - action.payload.num
      };
    default:
      return state;
  }
}

/*
* actions
* */

/*
* 发消息
* */
export function sendMsg ({from, to, content}) {
  return dispatch => {
    socket.emit("sendMsg", {from, to, content});
  }

}

/*读消息*/
export function readMsg (from) {
  return (dispatch, getState) => {
    axios.post('/user/msgRead', {from}).then(res => {
      const to = getState().user._id;
      if (res.status === 200 && res.data.code === 0) {
        dispatch(msgRead({from, to, num: res.data.num}));
      } else {
        console.log('msg read fail');
      }
    }).catch(e => {
      console.log('msg read err:', e.toString());
    });
  }
}

/*接受信息*/
export function recMsg (data) {
  return (dispatch, getState) => {
    socket.on('recMsg', data => {
      const userId = getState().user._id;
      dispatch(msgReceive(data, userId));
    });
  }
}

/*获取消息列表*/
export function getMsgList () {
  return (dispatch, getState) => {
    axios.get('/user/msgList').then(res => {
      if (res.status === 200 && res.data.code === 0) {
        const userId = getState().user._id;
        dispatch(msgList(res.data.data, userId))
      } else {
        console.log('msg err');
      }
    }).catch(e => {
      console.log(`msg err:${e.toString()}`);
    });
  }
}

/*
* action creator
* */
function msgList (data, userId) {
  return {type: MSG_LIST, payload: {...data, userId}};
}

function msgReceive (msg, userId) {
  return {type: MSG_REC, payload: {msg, userId}};
}

function msgRead ({from, to, num}) {
  return {type: MSG_READ, payload: {from, to, num}};
}